package com.pink.config;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pink.entity.dto.UserDto;
import com.pink.entity.enums.UserStatusEnum;
import com.pink.mappers.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class AccountDetailsService extends ServiceImpl<UserMapper, UserDto>
        implements UserDetailsService {

    // 正确注入全局配置的编码器
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String identifier) {
        UserDto user = this.lambdaQuery()
                .eq(UserDto::getUsername, identifier)
                .or()
                .eq(UserDto::getEmail, identifier)
                .oneOpt()
            .orElseThrow(() -> new UsernameNotFoundException("用户不存在"));
        // 账号封禁处理
        if (user.getUserStatus() == UserStatusEnum.BANNED.getCode()) {
            throw new UsernameNotFoundException("账号已被封禁");
        }
        return User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .authorities("ROLE_USER")
                .build();
    }
}

